package com.example.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/*
 * 发布确认 - 高级
 */
@Configuration
public class ConfirmConfig {

    //交换机
    private static final String CONFIRM_EXCHANGE_NAME = "confirm.exchange";
    //队列
    private static final String CONFIRM_QUEUE_NAME = "confirm.queue";
    //RoutingKey
    private static final String CONFIRM_ROUTING_KEY = "key1";
    //备份交换机
    private static final String BACKUP_EXCHANGE_NAME = "backup.exchange";
    //备份队列
    private static final String BACKUP_QUEUE_NAME = "backup.queue";
    //警告队列
    private static final String WARNING_QUEUE_NAME = "warning.queue";

    //声明交换机
    @Bean
    public DirectExchange confirmExchange() {
        /*
         * 构建交换机如果消息无法找到目标队列就投递给备份交换机
         * 备份交换机优先级高于消息回退
         */
        return ExchangeBuilder
                .directExchange(CONFIRM_EXCHANGE_NAME)
                .durable(true)
                .withArgument("alternate-exchange", BACKUP_EXCHANGE_NAME)
                .build();
    }

    //声明队列
    @Bean
    public Queue confirmQueue() {
        return QueueBuilder.durable(CONFIRM_QUEUE_NAME).build();
    }

    //绑定
    @Bean
    public Binding queueBindingExchange() {
        return BindingBuilder.bind(confirmQueue()).to(confirmExchange()).with(CONFIRM_ROUTING_KEY);
    }

    //声明备份交换机
    @Bean
    public FanoutExchange backupExchange() {
        return new FanoutExchange(BACKUP_EXCHANGE_NAME);
    }

    //声明备份队列
    @Bean
    public Queue backupQueue() {
        return QueueBuilder.durable(BACKUP_QUEUE_NAME).build();
    }

    //声明警告队列
    @Bean
    public Queue warningQueue() {
        return QueueBuilder.durable(WARNING_QUEUE_NAME).build();
    }

    //绑定
    @Bean
    public Binding backupQueueBindingBackExchange() {
        return BindingBuilder.bind(backupQueue()).to(backupExchange());
    }

    @Bean
    public Binding warningQueueBindingBackExchange() {
        return BindingBuilder.bind(warningQueue()).to(backupExchange());
    }

}
